import { commonParkingAddress } from '@/gql/filling';
import { toPublish } from '@mqtt';
import { defineStore } from 'pinia';
import { getDriverID } from './driverID';

type DeliveryInfo = {
  address: string;
  consignee: string;
  latitude: number;
  longitude: number;
  location: string;
  phone: string;
  name:string
};

export const useAddressStore = defineStore('address', {
  state: () => ({
    list: [],
    deliveryInfo: {
      address: '',
      consignee: '',
      latitude: null as number,
      longitude: null as number,
      location: '',
      phone: '',
	    name:''
    } as DeliveryInfo,
  }),
  getters: {
    defaultAddress(state) {
      if (state.list.find(({ is_default }) => is_default === '1')) {
        return state.list.find(({ is_default }) => is_default === '1');
      } else {
        this.deliveryInfo = {
          location: '',
          address: '',
          latitude: null,
          longitude: null,
          consignee: '',
          phone: '',
		      name:''
        };
      }
    },
  },
  actions: {
    getList(callback = () => { }) {
      const payload = {
        query: commonParkingAddress,
        variables: { driver_id: getDriverID() },
      };
      toPublish('ql/driver/getAddressList', payload, (obj: any) => {
        const { address_list } = obj.data;
        this.list = address_list === null ? [] : address_list;
        callback();
      });
    },
    clearDeliveryInfo() {
      this.deliveryInfo = {
        location: '',
        address: '',
        latitude: null,
        longitude: null,
        consignee: '',
        phone: '',
		    name:''
      };
    },
    setDeliveryInfo(info: DeliveryInfo) {
      this.deliveryInfo = info;
    },
    setDefaultDeliveryInfo() {
      const addr = this.defaultAddress;
      if (addr != undefined) {
		  console.log(JSON.stringify(addr))
        const info = {
          location: addr.abbreviate,
          address: addr.address,
          latitude: addr.latitude,
          longitude: addr.longitude,
          consignee: addr.consignee,
          phone: addr.phone,
		      name:addr.consignee
        };
        this.setDeliveryInfo(info);
      }
    },
  },
});
